package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private HttpSession httpSession;

    //发送验证码
    @PostMapping("/user/sendMsg")
    public ResultInfo sendMsg(@RequestBody Map<String, String> map) {
        //1. 接收参数
        String phone = map.get("phone");

        //2.生成验证码
        //String code = RandomUtil.randomNumbers(6);
        //todo 写死一个验证码为123 为了测试方便
        String code = "123";
        log.info("生成的验证码为:{}", code);

        //3. 将验证码保存到session中
        httpSession.setAttribute("SMS_" + phone, code);

        //todo 测试成功之后,将此段代码注释点,为了给其他同学留一条活路
        //4. 发送验证码到手机
        //smsTemplate.sendSms(phone, code);

        return ResultInfo.success(null);

    }

    //登录注册
    @PostMapping("/user/login")
    public ResultInfo login(@RequestBody Map<String, String> map) {
        String phone = map.get("phone");//用户输入的手机号
        String code = map.get("code");//用户输入的验证码
        String codeFromSession = (String) httpSession.getAttribute("SMS_" + phone);
        if (!code.equals(codeFromSession) || StringUtils.isEmpty(code) || StringUtils.isEmpty(codeFromSession)) {
            throw new CustomException("验证码错误");
        }
        //3. 根据phone从数据库查询
        User user = userService.findByPhone(phone);
        if (user == null){
            //如果数据库里没有,就插入数据库
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);//激活
            userService.save(user);
        }
        //4. 将user信息保存到session中(注意: 这个键必须跟拦截器中使用的键一致)
        httpSession.setAttribute("SESSION_USER", user);
        //如果走到这里,说明数据库里有该手机号,直接登陆
        return ResultInfo.success(user);
    }

    //退出登录
    @PostMapping("/user/logout")
    public ResultInfo loginOut(){
        userService.logOut();
        return ResultInfo.success(null);
    }
}
